package com.neo.push.client.handler;

import com.alibaba.fastjson.JSON;
import com.neo.push.client.listner.PushReceivedListener;
import com.neo.push.core.AcceptPush;
import com.neo.push.core.PushType;
import com.neo.push.core.Receipt;
import com.neo.push.core.SafetyPushText;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lock on 17-7-31.
 */
public class ClientMessageHandler extends ChannelInboundHandlerAdapter {

    private final PushReceivedListener receivedListener;

    public ClientMessageHandler(PushReceivedListener receivedListener) {
        this.receivedListener = receivedListener;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(!(msg instanceof SafetyPushText)){
            System.out.println(" not supported message ");
            return;
        }
        AcceptPush pushText =((SafetyPushText) msg).getMessage();
        ctx.writeAndFlush(new Receipt(pushText.getMessageId()));
        System.out.println("accepted origin push :"+JSON.toJSONString(pushText));
        List<AcceptPush> pushes = new ArrayList<AcceptPush>();
        splitText(pushText,pushes);
        for(AcceptPush acceptPush : pushes){
            receivedListener.receivedPush(acceptPush);
        }
    }


    private void splitText(AcceptPush push,List<AcceptPush> pushes){
        if(push.getPushType()== PushType.BUCKET){
            List<AcceptPush> list = JSON.parseArray(push.getContent(),AcceptPush.class);
            for(AcceptPush p : list){
                splitText(p,pushes);
            }
        }else{
            pushes.add(push);
        }
        System.out.println(" split push :"+JSON.toJSONString(pushes));
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
